<template>
  <div class="salary-schemes">
    <div class="page-header">
      <div class="page-title">薪资方案管理</div>
      <div class="header-actions">
        <el-button type="primary" @click="openAddDialog">
          <el-icon><Plus /></el-icon>新增方案
        </el-button>
      </div>
    </div>

    <div class="table-container">
      <el-table :data="schemes" border style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="name" label="方案名称" width="200" />
        <el-table-column prop="positionName" label="关联岗位" width="150" />
        <el-table-column prop="salaryType" label="计薪方式" width="120">
          <template #default="{ row }">
            <el-tag :type="getSalaryTypeTagType(row.salaryType)">
              {{ getSalaryTypeText(row.salaryType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="baseSalary" label="基本工资" width="120">
          <template #default="{ row }">
            ¥{{ formatMoney(row.baseSalary) }}
          </template>
        </el-table-column>
        <el-table-column prop="performanceRate" label="绩效系数" width="100" />
        <el-table-column prop="hourlyRate" label="时薪" width="100">
          <template #default="{ row }">
            ¥{{ formatMoney(row.hourlyRate) }}
          </template>
        </el-table-column>
        <el-table-column prop="commissionRate" label="提成比例" width="100">
          <template #default="{ row }">
            {{ row.commissionRate ? (row.commissionRate * 100).toFixed(1) + '%' : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="overtimeRate" label="加班费率" width="100">
          <template #default="{ row }">
            {{ row.overtimeRate }}倍
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status ? 'success' : 'danger'">
              {{ row.status ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="openEditDialog(row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="方案名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入方案名称" />
        </el-form-item>
        
        <el-form-item label="关联岗位" prop="positionId">
          <el-select v-model="form.positionId" placeholder="请选择岗位" style="width: 100%">
            <el-option
              v-for="position in positions"
              :key="position.id"
              :label="position.name"
              :value="position.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="计薪方式" prop="salaryType">
          <el-select v-model="form.salaryType" placeholder="请选择计薪方式" style="width: 100%">
            <el-option label="固定工资" value="FIXED" />
            <el-option label="绩效工资" value="PERFORMANCE" />
            <el-option label="时薪" value="HOURLY" />
            <el-option label="提成" value="COMMISSION" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="基本工资" prop="baseSalary">
          <el-input-number v-model="form.baseSalary" :precision="2" :step="100" :min="0" style="width: 100%" />
        </el-form-item>
        
        <el-form-item label="绩效系数" prop="performanceRate" v-if="form.salaryType === 'PERFORMANCE'">
          <el-input-number v-model="form.performanceRate" :precision="2" :step="0.1" :min="0" style="width: 100%" />
        </el-form-item>
        
        <el-form-item label="时薪" prop="hourlyRate" v-if="form.salaryType === 'HOURLY'">
          <el-input-number v-model="form.hourlyRate" :precision="2" :step="1" :min="0" style="width: 100%" />
        </el-form-item>
        
        <el-form-item label="提成比例" prop="commissionRate" v-if="form.salaryType === 'COMMISSION'">
          <el-input-number v-model="form.commissionRate" :precision="4" :step="0.001" :min="0" :max="1" style="width: 100%" />
        </el-form-item>
        
        <el-form-item label="加班费率" prop="overtimeRate">
          <el-input-number v-model="form.overtimeRate" :precision="2" :step="0.1" :min="1" style="width: 100%" />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-switch v-model="form.status" active-text="启用" inactive-text="禁用" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

const loading = ref(false)
const schemes = ref([])
const positions = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('新增薪资方案')
const isEdit = ref(false)
const formRef = ref(null)

const form = reactive({
  id: null,
  name: '',
  positionId: '',
  salaryType: 'FIXED',
  baseSalary: 0,
  performanceRate: 0,
  hourlyRate: 0,
  commissionRate: 0,
  overtimeRate: 1.5,
  status: true
})

const rules = {
  name: [{ required: true, message: '请输入方案名称', trigger: 'blur' }],
  positionId: [{ required: true, message: '请选择关联岗位', trigger: 'change' }],
  salaryType: [{ required: true, message: '请选择计薪方式', trigger: 'change' }],
  baseSalary: [{ required: true, message: '请输入基本工资', trigger: 'blur' }]
}

// 获取薪资方案列表
const fetchSchemes = async () => {
  try {
    loading.value = true
    const response = await axios.get('/salary/schemes')
    schemes.value = response.data
  } catch (error) {
    console.error('获取薪资方案失败:', error)
    ElMessage.error('获取薪资方案失败')
  } finally {
    loading.value = false
  }
}

// 获取岗位列表
const fetchPositions = async () => {
  try {
    const response = await axios.get('/positions')
    positions.value = response.data
  } catch (error) {
    console.error('获取岗位列表失败:', error)
  }
}

// 打开新增对话框
const openAddDialog = () => {
  isEdit.value = false
  dialogTitle.value = '新增薪资方案'
  Object.assign(form, {
    id: null,
    name: '',
    positionId: '',
    salaryType: 'FIXED',
    baseSalary: 0,
    performanceRate: 0,
    hourlyRate: 0,
    commissionRate: 0,
    overtimeRate: 1.5,
    status: true
  })
  dialogVisible.value = true
}

// 打开编辑对话框
const openEditDialog = (row) => {
  isEdit.value = true
  dialogTitle.value = '编辑薪资方案'
  Object.assign(form, row)
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        
        if (isEdit.value) {
          await axios.put(`/salary/schemes/${form.id}`, form)
          ElMessage.success('薪资方案更新成功')
        } else {
          await axios.post('/salary/schemes', form)
          ElMessage.success('薪资方案创建成功')
        }
        
        fetchSchemes()
        dialogVisible.value = false
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('操作失败，请重试')
      } finally {
        loading.value = false
      }
    }
  })
}

// 删除方案
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除薪资方案 "${row.name}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      loading.value = true
      await axios.delete(`/salary/schemes/${row.id}`)
      ElMessage.success('删除成功')
      fetchSchemes()
    } catch (error) {
      console.error('删除失败:', error)
      if (error.response && error.response.data && error.response.data.message) {
        ElMessage.error(error.response.data.message)
      } else if (error.message) {
        ElMessage.error(error.message)
      } else {
        ElMessage.error('删除失败，请重试')
      }
    } finally {
      loading.value = false
    }
  }).catch(() => {})
}

// 格式化金额
const formatMoney = (amount) => {
  if (!amount) return '0.00'
  return Number(amount).toFixed(2)
}

// 获取计薪方式标签类型
const getSalaryTypeTagType = (type) => {
  const types = {
    'FIXED': 'success',
    'PERFORMANCE': 'warning',
    'HOURLY': 'info',
    'COMMISSION': 'danger'
  }
  return types[type] || 'default'
}

// 获取计薪方式文本
const getSalaryTypeText = (type) => {
  const texts = {
    'FIXED': '固定工资',
    'PERFORMANCE': '绩效工资',
    'HOURLY': '时薪',
    'COMMISSION': '提成'
  }
  return texts[type] || type
}

onMounted(() => {
  fetchSchemes()
  fetchPositions()
})
</script>

<style scoped>
.salary-schemes {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 18px;
  font-weight: bold;
}

.table-container {
  margin-top: 20px;
}
</style> 